<template>
  <view class="index-box"></view>
</template>

<script>
import { USER_ROLE } from '@/constant/index.js'
export default {
  data() {
    return {
      params: {}
    }
  },
  onLoad(option) {
    const self = this
    Object.assign(self.params, option)
  },
  mounted() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      const self = this
      uni.request({
        url: '/user/get',
        success(result) {
          if (result.data.success && result.data.data) {
            const userInfo = result.data.data
            self.isAdmin = userInfo.role === USER_ROLE.ADMIN
            self.canEdit = [USER_ROLE.ADMIN, USER_ROLE.AGENT].includes(userInfo.role)
            self.$forceUpdate()
            uni.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            self.toIndex()
          }
        }
      })
    },
    toIndex() {
      const app = getApp()
      const { qrGatewayId, qrVideoId, targetProjectId } = app.globalData
      const paramsArr = []
      if (qrGatewayId) {
        paramsArr.push(`gatewayId=${qrGatewayId}`)
      }
      if (qrVideoId) {
        paramsArr.push(`videoId=${qrVideoId}`)
      }
      if (targetProjectId) {
        paramsArr.push(`projectId=${targetProjectId}`)
      }
      let paramsStr = ''
      if (paramsArr.length) {
        paramsStr = `?${paramsArr.join('&')}`
      }
      uni.reLaunch({
        url: `/pages/index/index/index${paramsStr}`
      })
    },
    getProjectList() {
      const self = this
      uni.request({
        url: '/project/list',
        data: {},
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const projectItem = {
                key: item.id,
                projectId: item.id,
                name: item.name || '',
                locationInfo: item.address || '',
                userName: item.user_name || '',
                phone: item.phone || '',
                online: !!item.online
              }
              arr.push(projectItem)
            })
            if (arr.length === 1) {
              self.toProjectDetail(arr[0])
            } else {
              self.toProjectList()
            }
          }
        }
      })
    },
    toProjectList() {
      const self = this
      uni.reLaunch({
        url: '/pages/index/project-list/project-list'
      })
    },
    toProjectDetail(project) {
      uni.reLaunch({
        url: `/pages/project-detail/index/index?id=${project.projectId}`
      })
    }

  }
}
</script>

<style>

</style>
